package com.gem.day14.homework;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/*文件拆分和合并*/
public class Exercise3 {

	/** 每个小文件大小 */
	static final int SIZE = 1024 * 1024;
	/** 需要分割的文件 */
	static final String SOURCE = "F:/java/JetbrainsCrack-2019.3.2.jar";
	/** 分割后输出的目录 */
	static final String SOURCE_OUT = "F:/temp/";
	/** 合并后的文件 */
	static final String DST = "F:/JetbrainsCrack.jar";

	public static void main(String[] args) {

		/*
		 * try { split(); } catch (Exception e) { e.printStackTrace(); }
		 */

		try {
			merge();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 文件分割
	 * 
	 * @throws FileNotFoundException
	 * 
	 * @throws IOException
	 */
	public static void split() throws Exception {

		File file = new File(SOURCE);
		FileInputStream raf = new FileInputStream(file);
		FileChannel fc = raf.getChannel();
		long fileSize = fc.size();

		int count = (int) (fileSize / SIZE);
		ByteBuffer dst = ByteBuffer.allocate(SIZE);
		for (int i = 0; i <= count; i++) {
			FileOutputStream fs = new FileOutputStream(new File(SOURCE_OUT + i));
			if (i != count) {
				fc.read(dst, SIZE * i);
				fs.write(dst.array());
			} else {
				fileSize = fileSize - SIZE * count;
				ByteBuffer dstTail = ByteBuffer.allocate((int) fileSize);
				fs.write(dstTail.array());
			}
			fs.flush();
			dst.clear();
		}
	}

	/**
	 * 合并文件
	 * 
	 * @throws Exception
	 */
	public static void merge() throws Exception {
		File parentFile = new File(SOURCE_OUT);
		File fileDst = new File(DST);
		FileChannel fs = new FileOutputStream(fileDst, true).getChannel();
		try {
			for (File file : parentFile.listFiles()) {
				FileChannel fc = new FileInputStream(file).getChannel();
				ByteBuffer by = ByteBuffer.allocate((int) fc.size());
				fc.read(by);
				by.position(0);
				fs.write(by);
			}
		} finally {
			fs.close();
		}
	}
}
